include_class "java.lang.System"
include_class "java.io.Console"

JString=java.lang.String

class CommandTemplate < CmdParse::Command
  def initialize(name,desc='',short_desc='')
    super(name, false )
    self.short_desc = short_desc
    self.description = desc
    self.options = CmdParse::OptionParserWrapper.new do |opt|
      opt.on( '-out',  'custom output' ) { $customout = true }
      opt.on( '-notinter',  'not interactive (user name and password are inlined)' ) { $notinter = true }
    end
    @console=System::console()
    @args_not_valid = lambda { |args| (args.empty? || args.length < 2) }
  end

  def basic_flow(args,service,fetch_message)
    begin

      if($notinter)
        puts '# You must pass your user name and password!' or return  if @args_not_valid.call(args)
        user,pass=args
      else
        puts '# Enter user name' or user = @console.readLine()
        puts '# Enter password' or pass = JString.new(@console.readPassword())
      end
      
      puts '# Logging in'
      service.login(user, pass)
      puts '# Fetching data'
      service.send(fetch_message)
      output_setup(args)
      puts '# Persisting the result to '+Settings[:output]
      service.persist
    rescue Exception => e
      puts e.message
    end
  end

  def output_setup(args)
    index=args.size-1
    if $customout
      if (File.exist?(args[index]) && File.directory?(args[index]))
        Settings[:output]=args[index]
        puts '# Custom output set'
      else
        puts '# Supplied output path isn\'t legal, default one will be used.'
      end
    end
  end

end
